from rest_framework import serializers

from login import models


class UserAuthModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserAuthModel
        fields = '__all__'


class UserDetailModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserDetailModel
        fields = '__all__'


class UserModelSerializer(serializers.ModelSerializer):
    auth = UserAuthModelSerializer(required=False, allow_null=True)
    detail = UserDetailModelSerializer(required=False, allow_null=True)

    class Meta:
        model = models.UserModel
        fields = '__all__'
        extra_kwargs = {
            'password': {'write_only': True}  # 密码设为仅写入
        }

    def create(self, validated_data):
        # 处理嵌套对象创建
        auth_data = validated_data.pop('auth', None)
        detail_data = validated_data.pop('detail', None)

        # 创建主用户
        user = models.UserModel.objects.create(**validated_data)

        # 创建关联的实名认证
        if auth_data:
            models.UserAuthModel.objects.create(user=user, **auth_data)

        # 创建关联的详情
        if detail_data:
            models.UserDetailModel.objects.create(user=user, **detail_data)

        return user

    def update(self, instance, validated_data):
        # 更新主字段
        instance.password = validated_data.get('password', instance.password)
        instance.phone = validated_data.get('phone', instance.phone)
        instance.save()

        # 更新实名认证
        auth_data = validated_data.get('auth')
        if auth_data:
            auth_instance = instance.auth
            if auth_instance:
                for attr, value in auth_data.items():
                    setattr(auth_instance, attr, value)
                auth_instance.save()
            else:
                # 如果不存在则创建
                models.UserAuthModel.objects.create(user=instance, **auth_data)

        # 更新用户详情
        detail_data = validated_data.get('detail')
        if detail_data:
            detail_instance = instance.detail
            if detail_instance:
                for attr, value in detail_data.items():
                    setattr(detail_instance, attr, value)
                detail_instance.save()
            else:
                # 如果不存在则创建
                models.UserDetailModel.objects.create(user=instance, **detail_data)

        return instance